import os
import time

from src2.BaseThread import BaseThread
from src2.FrameParser import FrameParser


class FileMonitor(BaseThread):
    def __init__(self, dir):
        BaseThread.__init__(self, "FileMonitor", 1)
        self.file_index = 0
        self.frame_parser = FrameParser()
        self.dir_path = dir
        self.files = []

    def pre_job(self):
        self.files = os.listdir(self.dir_path)
        self.files.sort(key=lambda x: int(x[:-4]))

    def after_job(self):
        pass

    def real_job(self):
        if self.file_index >= len(self.files):
            return False

        self.print(str(self.file_index) + '/' + str(len(self.files) - 1) + '  ' + self.files[self.file_index])

        file = self.dir_path + "/" + self.files[self.file_index]
        self.file_index += 1

        with open(file, 'r') as f:
            lines = f.readlines()
            for line in lines:
                if len(line) > 0:
                    self.frame_parser.parse_line(line[:-1])
                elif line == '':
                    break

        return True

    def run_until_finish(self):
        start = time.time()
        self.start()
        self.thread.join()
        end = time.time()
        self.print('elapsed ' + str(end - start) + " seconds.")

    def get_info(self):
        rank = self.frame_parser.get_mem_rank()
        status = self.frame_parser.get_mem_status()
        return {'rank': rank, 'mem': status}
